<script lang="ts" setup>

const props = defineProps({
    amount: {
        type: [String, null] as PropType<string | null>,
        default: ""
    }
})

watch(
  () => props.amount, 
  (newAge, oldAge) => {
    activeIndexes.value.forEach(index => {
      list.value[index] = newAge
    })
  }
)

let activeIndexes = ref([])
let list = ref(Array(12).fill(""))
// 全选/反选
const toggleSelect = () => {
    if (activeIndexes.value.length === 12) {
        activeIndexes.value = []
        list.value = Array(12).fill("")
    } else {
        activeIndexes.value = list.value.map((_, index) => index)
        list.value = Array(12).fill(props.amount)
    }
    changeHandle()
}
const select = (index) => {
    if (activeIndexes.value.includes(index)) {
        list.value[index] = ""
        activeIndexes.value = activeIndexes.value.filter((item) => item !== index)
    } else {
        list.value[index] = props.amount
        activeIndexes.value.push(index)
    }
    changeHandle()
}


// 定义 emit 事件
const emit = defineEmits<{
    (event: 'change', list: any[]): void
}>()

const changeHandle = () => {
    emit("change", list.value)
}
</script>

<template>
    <view class="select-month">
        <view class="flex items-center justify-between mb-10rpx">
            <view>
                <view class="font-size-28rpx color-#000000">选择月份自动计算</view>
                <view class="font-size-24rpx mt-10rpx" style="color: var(--sar-warning)">金额不同的月份可手动填写</view>
            </view>
            <view>
                <sar-button type="default" @click="toggleSelect">
                    {{ activeIndexes.length === 12 ? "取消全选" : "一键全选" }}
                </sar-button>
            </view>
        </view>
        <sar-row :gap="30">
            <template v-for="(item, index) in list" :key="index">
                <sar-col :span="4">
                    <view class="my-15rpx">
                        <sar-button
                            :background="activeIndexes.includes(index) ? 'rgba(var(--sar-primary-rgb), 0.5)' : '#7c7e8b1a'"
                            color="#666" @click="select(index)">
                            {{ index + 1 }}月
                        </sar-button>
                    </view>
                    <view class="mb-10rpx" v-if="activeIndexes.includes(index) && activeIndexes.length">
                        <sar-input v-model="list[index]" placeholder="金额" inputmode="numeric" type="digit"
                            @input="changeHandle" />
                    </view>
                </sar-col>
            </template>
        </sar-row>
    </view>
</template>

<style lang="scss" scoped></style>